package net.p2pcdn.email.service;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 *
 * 类名称：MailUtil 类描述： 创建人：zx 修改人：zx 修改时间：2016年4月23日
 * 
 * @version 1.0.0
 *
 */
public class JavaMailSender {
	private static final Logger _logger = LoggerFactory.getLogger(JavaMailSender.class);

	/**
	 * 
	 * @param config
	 *            邮箱配置信息
	 * @param acceptEmail
	 *            接受人
	 * @param title
	 *            标题
	 * @param content
	 *            内容
	 * @return
	 * @throws MessagingException
	 * @throws UnsupportedEncodingException
	 */
	public static boolean sendMail(MailConfig config, String acceptEmail, String title, String content)
			throws MessagingException, UnsupportedEncodingException {
		// 配置发送邮件的环境属性
		final Properties props = new Properties();
		// 表示SMTP发送邮件，需要进行身份验证
		props.put("mail.smtp.auth", config.isAuth());
		props.put("mail.smtp.host", config.getSmtpHost());
		// 发件人的账号
		props.put("mail.user", config.getUser());
		// 访问SMTP服务时需要提供的密码
		props.put("mail.password", config.getPassword());
		props.setProperty("mail.transport.protocol", "smtp");
		props.setProperty("mail.smtp.port", config.getPort());
		props.setProperty("mail.smtp.starttls.enable", "true");
		// 设置发件人名称
		props.put("mail.sendName", config.getSendName());
		// 构建授权信息，用于进行SMTP进行身份验证
		Authenticator authenticator = new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				// 用户名、密码
				String userName = props.getProperty("mail.user");
				String password = props.getProperty("mail.password");
				return new PasswordAuthentication(userName, password);
			}
		};
		// 使用环境属性和授权信息，创建邮件会话
		Session mailSession = Session.getInstance(props, authenticator);
		// 创建邮件消息
		MimeMessage message = new MimeMessage(mailSession);
		// 设置发件人
		InternetAddress form = new InternetAddress(props.getProperty("mail.user"), props.getProperty("mail.sendName"));
		message.setFrom(form);

		// 设置收件人
		InternetAddress to = new InternetAddress(acceptEmail);
		try {
			to.validate();
		} catch (Exception e) {
			throw new RuntimeException("邮箱地址不存在");
		}
		message.setRecipient(RecipientType.TO, to);
		// 设置邮件标题
		message.setSubject(title);

		// 设置邮件内容
		message.setContent(content, "text/html;charset=UTF-8");
		// 发送邮件
		try {
			Transport.send(message);
			return Boolean.TRUE;
		} catch (Exception e) {
			_logger.error(e.getMessage(), e);
			return Boolean.FALSE;
		}
	}

	public static void main(String[] args) throws UnsupportedEncodingException, MessagingException {
//		MailConfig config = MailConfig.builder().auth(true).port("587").password("P2Pcdn123...").user("support@p2pcdn.net").sendName("p2pcdn").smtpHost("smtp.office365.com").build();
//		sendMail(config,"xin.zhang@ghrlib.com","demo","123456");
	}
}
